package com.whjz.manage.utils;

import com.whjz.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.collections4.bidimap.TreeBidiMap;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

/**
 * @version 1.0
 * @Description 文件报表下载
 * @Author lcc
 * @Date 2019/5/24 16:29
 **/
@Slf4j
public class FileUtils {


    static String videoPathUrl; //影像系统path 没用的
    @Value("${path.managePicUrl}")
    static String managePath; //影像系统path

    /**
     * @return
     * @author ： lcc
     * @DEsc :导出模板文件
     * @date: 2019/5/24 19:18
     * @Param: null
     */
    public static void export(Map<String, Object> mapFill, String fileName, String model, HttpServletRequest request, HttpServletResponse response) {

        response.setContentType("application/vnd.ms-excel;charset=GB2312");
        String rp = "exceltemplate";
        String path = request.getSession().getServletContext().getRealPath(rp);
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        JexlEngine s = new JexlEngine();
        TreeBidiMap tt = new TreeBidiMap();
        XLSTransformer transformer = new XLSTransformer();
        try {
            File file = new File(fileName);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            Resource rource = new ClassPathResource("exceltemplate" + File.separator + model);
            InputStream in = rource.getInputStream();
            if (null == in) {
                return;
            }
            FileCopyUtils.copy(FileCopyUtils.copyToByteArray(in), new File(path + File.separator + model));
            transformer.transformXLS(path + File.separator + model, mapFill, path + File.separator + model + "_temp");
            try {
                response.setHeader("Content-disposition",
                        "attachment;success=true;filename ="
                                + URLEncoder.encode(fileName, "utf-8"));
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;
                OutputStream fos = null;
                InputStream fis = null;
                File uploadFile = new File(path + File.separator + model + "_temp");
                fis = new FileInputStream(uploadFile);
                bis = new BufferedInputStream(fis);
                fos = response.getOutputStream();
                bos = new BufferedOutputStream(fos);
                // 弹出下载对话框
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
                    bos.write(buffer, 0, bytesRead);
                }
                bos.flush();
                fis.close();
                bis.close();
                fos.close();
                bos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String uploadFile(MultipartFile file, String videoPathUrl, String type) {
        return uploadFile(file, videoPathUrl, type, false);
    }

    /**
     * @return
     * @author ： lcc
     * @DEsc :上传文件
     * @date: 2019/5/25 12:37
     * @Param: null
     */
    public static String uploadFile(MultipartFile file, String videoPathUrl, String type, boolean isVideo) {
        String str = null;
        try {
            String fileName = URLDecoder.decode(file.getOriginalFilename(), "UTF-8");
            String prefix = fileName.substring(fileName.lastIndexOf("."));
            /**一下是将文件类型转变方便传输 开始*/
            String dateStr = DateUtils.getCurDate("yyyyMMdd");
            String dirPath = videoPathUrl;
//            dirPath="D:/共享文件";
            if (StringUtils.isBlank(type)) {
                type = prefix;
            }
            String filePath = dirPath + "/manage/" + dateStr + "/" + type;
            if ("temp".equals(type)) {
                filePath = dirPath + "/temp/" + dateStr + "/";
            }
            File dir = new File(filePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            log.info("文件所在目录:" + filePath);
            String uuid = UUID.randomUUID().toString();
            final File exceFile = File.createTempFile(uuid, prefix, dir);
            file.transferTo(exceFile);
            str = exceFile.getAbsolutePath();
            str = str.replace(videoPathUrl, "");
        } catch (IOException e) {
            log.error("上传文件异常", e);
        }
        return str;
    }

////新增的20190923
//    /**
//     * 生成后管文件存储文件的文件名规则如下：
//     * 1./image/日期/机构/柜员/前端流水号
//     * @param baseInfo
//     * @param basePath
//     * @return
//     */
//    public static Map getUploadFilePathToManage(MultipartFile uploadFile,BaseInfo baseInfo, String basePath, String imageType){
//        String uploadFilePath= FilesUtil.getUploadFilePathToManage(baseInfo,"image","product");
//        String filename=FilesUtil.uploadMulToLoaclImage(uploadFile,uploadFilePath);
//        if(!com.whjz.utils.StringUtils.isNotNullOrEmtory(filename)){
//            return ResultUtil.resultMap("Mul文件存放服务端出错", ResultCode.RESUTL_CODE_FAILURE.code(),new HashMap<>());
//        }
//        return ResultUtil.resultMap("Mul文件存放服务端出错", ResultCode.RESUTL_CODE_FAILURE.code(),new HashMap<>());
//    }
}
